#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库管理脚本
提供数据库初始化、重置、备份等管理功能
"""

import os
import sys
import argparse
import logging
from datetime import datetime
from api_restructured import create_app
from .database import create_tables, drop_tables, reset_database
from models.base import db
from models import User, Message, Group, Config, WelcomeRecord, Belong

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def init_db():
    """
    初始化数据库
    """
    logger.info("开始初始化数据库...")
    app = create_app()
    
    with app.app_context():
        create_tables(app)
    
    logger.info("数据库初始化完成")

def reset_db():
    """
    重置数据库（删除所有数据）
    """
    confirm = input("⚠️  警告：此操作将删除所有数据，是否继续？(y/N): ")
    if confirm.lower() != 'y':
        logger.info("操作已取消")
        return
    
    logger.info("开始重置数据库...")
    app = create_app()
    
    with app.app_context():
        reset_database(app)
    
    logger.info("数据库重置完成")

def backup_db():
    """
    备份数据库
    """
    db_path = os.path.join(os.path.dirname(__file__), 'wechat_robot.db')
    
    if not os.path.exists(db_path):
        logger.error("数据库文件不存在，无法备份")
        return
    
    # 生成备份文件名
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    backup_path = os.path.join(os.path.dirname(__file__), f'wechat_robot_backup_{timestamp}.db')
    
    try:
        import shutil
        shutil.copy2(db_path, backup_path)
        logger.info(f"数据库备份成功: {backup_path}")
    except Exception as e:
        logger.error(f"数据库备份失败: {e}")

def show_tables():
    """
    显示数据库表信息
    """
    logger.info("查询数据库表信息...")
    app = create_app()
    
    with app.app_context():
        try:
            # 获取表统计信息
            tables_info = [
                ('users', User.query.count(), '用户表'),
                ('groups', Group.query.count(), '群组表'),
                ('messages', Message.query.count(), '消息表'),
                ('configs', Config.query.count(), '配置表'),
                ('welcome_records', WelcomeRecord.query.count(), '欢迎记录表'),
                ('belongs', Belong.query.count(), '归属表')
            ]
            
            print("\n📊 数据库表统计信息:")
            print("-" * 50)
            for table_name, count, description in tables_info:
                print(f"{description:12} ({table_name:15}): {count:6} 条记录")
            print("-" * 50)
            
        except Exception as e:
            logger.error(f"查询表信息失败: {e}")

def show_configs():
    """
    显示系统配置
    """
    logger.info("查询系统配置...")
    app = create_app()
    
    with app.app_context():
        try:
            configs = Config.query.order_by(Config.category, Config.config_key).all()
            
            if not configs:
                print("\n❌ 没有找到任何配置")
                return
            
            print("\n⚙️  系统配置列表:")
            print("-" * 80)
            
            current_category = None
            for config in configs:
                if config.category != current_category:
                    current_category = config.category
                    print(f"\n📁 {current_category.upper()}:")
                
                status = "✅" if config.is_enabled else "❌"
                system_mark = "🔒" if config.is_system else "📝"
                print(f"  {status} {system_mark} {config.config_key:30} = {config.config_value}")
                if config.description:
                    print(f"      📝 {config.description}")
            
            print("-" * 80)
            print("说明: ✅=启用 ❌=禁用 🔒=系统配置 📝=用户配置")
            
        except Exception as e:
            logger.error(f"查询配置失败: {e}")

def main():
    """
    主函数
    """
    parser = argparse.ArgumentParser(description='微信机器人数据库管理工具')
    parser.add_argument('action', choices=['init', 'reset', 'backup', 'tables', 'configs'], 
                       help='要执行的操作')
    
    args = parser.parse_args()
    
    print("🤖 微信机器人数据库管理工具")
    print("=" * 40)
    
    try:
        if args.action == 'init':
            init_db()
        elif args.action == 'reset':
            reset_db()
        elif args.action == 'backup':
            backup_db()
        elif args.action == 'tables':
            show_tables()
        elif args.action == 'configs':
            show_configs()
    except KeyboardInterrupt:
        print("\n👋 操作被用户中断")
    except Exception as e:
        logger.error(f"操作失败: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()